package com.kuaiditu.assistant.api.xz_api.xz_encode;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by Eenie on 2017/8/11.
 * Email: eeniework@gmail.com
 * Des:
 */

public class XingZheEncodeUtil {

    static Cipher sCipher;

    public static String encode(String src, String key)  {

        try {
            return hexSrc(encodeByte(src.getBytes(), key));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    public static Key getKey(String key) throws Exception {
        String k = key;
        if (key == null) {
            k = "0000";
        }
        return new SecretKeySpec((k + "0000000000000000000000000000").getBytes("UTF-8"), "AES");
    }


    public static String hexSrc(byte[] src) {
        StringBuffer stringBuffer = new StringBuffer();
        int i = 0;
        while (i < src.length)
        {
            String str2 = Integer.toHexString(src[i] & 0xFF);
            String str1 = str2;
            if (str2.length() == 1) {
                str1 = '0' + str2;
            }
            stringBuffer.append(str1.toUpperCase());
            i += 1;
        }
        return stringBuffer.toString();


    }

    private static void initCipher() {
        try {
            sCipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    public static byte[] encodeByte(byte[] srcByte, String key) throws Exception {
        Key k = getKey(key);
        if (sCipher == null) {
            initCipher();
        }
        sCipher.init(1, k);



        return sCipher.doFinal(srcByte);
    }






}
